import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;

public class AccessingPackagedResources {

	public static void main(String[] args) throws IOException {
		File currentDir = new File(".");
		System.out.println("The current directory is: " + currentDir.getCanonicalPath());
		System.out.println();

		System.out.println("Finding a resource in the classpath ...");
		AccessingPackagedResources example = new AccessingPackagedResources();
		example.findAndPrintResource("docs/pesho.txt");
		System.out.println();

		System.out.println("Finding a resource in a JAR file in the classpath ...");
		example.findAndPrintResource("folderInJarFile/resourceInJarFile.txt");
		System.out.println();

		System.out.println("Finding a non-existing resource ...");
		example.findAndPrintResource("non-existing-resource.txt");
	}

	private void findAndPrintResource(String resourceName) throws IOException {
		InputStream resourceStream = this.getClass().getResourceAsStream(resourceName);
		if (resourceStream == null) {
			throw new FileNotFoundException("Can not find file '" + resourceName + "' in the classpath.");
		}
		try {
			Scanner scanner = new Scanner(resourceStream);
			while (scanner.hasNextLine()) {
				System.out.println(scanner.nextLine());
			}
		} finally {
			resourceStream.close();
		}
	}

}